package com.google.code.jgchart;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;

public class Label implements UrlQuery {

	private static final String LABEL_PARAM = "chl=";

	private String urlCodec = "UTF-8";

	private List<String> labels = new ArrayList<String>();

	public Label() {
	}

	public Label setUrlCodec(String urlCodec) {
		this.urlCodec = urlCodec;
		return this;
	}

	public Label append(String legend) {
		if (legend == null) {
			throw new IllegalArgumentException("legend can't be null.");
		}
		labels.add(legend);
		return this;
	}

	public String[] getQuery() {
		if (labels.size() == 0) {
			return new String[] { "" };
		}
		StringBuilder sb = new StringBuilder();
		URLCodec codec = new URLCodec(urlCodec);
		try {
			sb.append(LABEL_PARAM).append(codec.encode(labels.get(0)));
		} catch (EncoderException e) {
			throw genQueryEncoderException(labels.get(0), urlCodec, e);
		}
		String split = "|";
		for (int i = 1; i < labels.size(); i++) {
			try {
				sb.append(codec.encode(split));
			} catch (EncoderException e) {
				throw genQueryEncoderException("split: " + split, urlCodec, e);
			}
			try {
				sb.append(codec.encode(labels.get(i)));
			} catch (EncoderException e) {
				throw genQueryEncoderException(labels.get(i), urlCodec, e);
			}
		}

		return new String[] { sb.toString() };
	}

	private QueryEncoderException genQueryEncoderException(String data,
			String codec, Throwable cause) {
		return new QueryEncoderException("label(" + data + ") encode(" + codec
				+ ") error.", cause);
	}

}
